package com.ascentive.finallyfast.deepclean;

import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.ascentive.finallyfast.BaseActivity;
import com.ascentive.finallyfast.R;

public class DeepCleanPage extends BaseActivity implements
		DeepCleanViewListener, DeepCleanListAdapterListener {

	private DeepCleanListExpandableAdapter expListAdapter;
	private ArrayList<DeepCleanListItem> mGroupNames = null;
	private ArrayList<ArrayList<DeepCleanListItem>> mChildrenNames = null;
	private DeepCleanView mDeepCleanView = null;
	DeepCleanListAdapter mDeepCleanListAdapter = null;
	static final private int SELECT_DURATION_DIALOG = 1;
	static final private int CONFIRMATION_DIALOG = 2;
	static final private int CLEAN_STATUS_DIALOG = 3;
	// categories in Deep Clean feature
	public static final int CALL_LOG = 0;
    public static final int SMS = 1;
    public static final int BROWSER_HISTORY = 2;
    public static final int CLIPBOARD = 3;
    public static final int GOOGLE_MAPS_SEARCH_HISTORY = 4;
    public static final int GMAIL_MAPS_SEARCH_HISTORY = 5;
    public static final int MARKET_SEARCH_HISTORY = 6;
    ProgressDialog cleanningProgDialog = null;
    /*
    public static final int MARKET_SEARCH_HISTORY = 4;
    public static final int YOUTUBE_SEARCH_HISTORY = 5;
    public static final int GMAIL_SEARCH_HISTORY = 6;
    public static final int GOOGLE_SEARCH_HISTORY = 7;
    public static final int GOOGLE_MAPS_SEARCH_HISTORY = 8;
    public static final int GOOGLE_EARTH_SEARCH_HISTORY = 9;
    public static final int ALL_APP_CACHE = 10;
   */
    // Categories to select duration for clearing junk files
    public static final int DAY = 0;
    public static final int WEEK = 1;
    public static final int MONTH = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDeepCleanView = new DeepCleanView(getFinallyFastApplication());
		setContentView(mDeepCleanView);
		mDeepCleanView.setListener(this);

		mGroupNames = new ArrayList<DeepCleanListItem>();
		
		mGroupNames.add(new CallLogHistory(getFinallyFastApplication(), this
				.getResources().getString(R.string.call_log), false,
				R.drawable.call_log));
		mGroupNames.add(new SmsLog(getFinallyFastApplication(), this
				.getResources().getString(R.string.sms), false,
				R.drawable.sms_log));
		mGroupNames.add(new ClipboardData(getFinallyFastApplication(), this
				.getResources().getString(R.string.clipboard_data), false,
				R.drawable.clipboard));
		mGroupNames.add(new BrowserHistory(getFinallyFastApplication(), this
				.getResources().getString(R.string.browser_search_history),
				false, R.drawable.browser_history));
		mGroupNames.add(new GMapsSearchHistory(getFinallyFastApplication(),
				this.getResources().getString(
						R.string.google_maps_search_history), false,
				R.drawable.mapsearch_history));
		mGroupNames.add(new GmailSearchHistory(getFinallyFastApplication(),
				this.getResources().getString(R.string.gmail_search_history),
				false, R.drawable.gmail_client_history));
		mGroupNames.add(new MarketSearchHistory(getFinallyFastApplication(),
				this.getResources().getString(
						R.string.android_market_serach_history), false,
				R.drawable.mapsearch_history));
		
		mChildrenNames = new ArrayList<ArrayList<DeepCleanListItem>>();
		
		ArrayList<DeepCleanListItem> calllist = new ArrayList<DeepCleanListItem>();
		calllist.add(new CallOutgoingHistory(getFinallyFastApplication(), "Outgoing Calls", false, R.drawable.call_log));
		calllist.add(new CallIncomingHistory(getFinallyFastApplication(), "Incoming Calls", false, R.drawable.call_log));
		calllist.add(new CallMissedHistory(getFinallyFastApplication(), "Missed Calls", false, R.drawable.call_log));
		mChildrenNames.add(calllist);
		
		ArrayList<DeepCleanListItem> smslist = new ArrayList<DeepCleanListItem>();
		smslist.add(new SmsInboxLog(getFinallyFastApplication(), "Inbox", false, R.drawable.sms_log));
		smslist.add(new SmsSentLog(getFinallyFastApplication(), "Sent Items", false, R.drawable.sms_log));
		smslist.add(new SmsDraftsLog(getFinallyFastApplication(), "Drafts", false, R.drawable.sms_log));
		mChildrenNames.add(smslist);
		
		ArrayList<DeepCleanListItem> clipboardlist = null;
		ArrayList<DeepCleanListItem> browserlist = null;
		ArrayList<DeepCleanListItem> gmapslist = null;
		ArrayList<DeepCleanListItem> gmaillist = null;
		ArrayList<DeepCleanListItem> marketlist = null;
		
		mChildrenNames.add(clipboardlist);
		mChildrenNames.add(browserlist);
		mChildrenNames.add(gmapslist);
		mChildrenNames.add(gmaillist);
		mChildrenNames.add(marketlist);
		
		expListAdapter = new DeepCleanListExpandableAdapter( this, mGroupNames, mChildrenNames );
		//mDeepCleanListAdapter.setListener(this);
		expListAdapter.setListener(this);
		// expListAdapter.setListAdapter( expListAdapter );
		
		if (mDeepCleanView != null)
			mDeepCleanView.setAdapter(expListAdapter);
		// Expand all groups at the start
		mDeepCleanView.expandAllGroups();
	}
	
	/** Creating Alert Dialog when clear button is pressed */
	@Override
	protected Dialog onCreateDialog(int id) {
		
		LayoutInflater li;
		
		switch (id) {
		case SELECT_DURATION_DIALOG:
			li = LayoutInflater.from(this);
			View selectdurationView = li.inflate(R.layout.deep_clean_select_duration_dialog, null);
			AlertDialog.Builder selectDurationDialogBuilder = new AlertDialog.Builder(this);
						
			selectDurationDialogBuilder.setView(selectdurationView);

			TextView headingtv = (TextView)selectdurationView.findViewById(R.id.headingText);
			headingtv.setText(R.string.select_duration_dialog_heading);
			
			final String [] arrayItems = new String[]{"Days", "Weeks", "Months"};
            ArrayAdapter<String> ad = new ArrayAdapter<String>(this, 
            							  android.R.layout.simple_list_item_single_choice,
            							  arrayItems);
            // Set ListView
            ListView lv = (ListView)selectdurationView.findViewById(R.id.list);
            lv.setAdapter(ad);
            lv.setItemChecked(WEEK, true);
            setTheme(0x1020022);
            // Set Listener
			lv.setOnItemClickListener(new OnItemClickListener() {
				
				public void onItemClick(AdapterView arg0, View arg1, int arg2,
						long arg3) {
					
					LayoutInflater li = LayoutInflater.from(DeepCleanPage.this);
					View selectdurationView = li.inflate(R.layout.deep_clean_select_duration_dialog, null);
					
					com.ascentive.finallyfast.NumberPicker np = 
						(com.ascentive.finallyfast.NumberPicker)selectdurationView.findViewById(R.id.numpick);
					switch(arg2)
					{
						case DAY: // day
							System.out.println("DAY");
							np.setRange(1, 1095);
							break;
						case WEEK: // week
							System.out.println("WEEK");
							np.setRange(1, 157);
							break;
						case MONTH: // month
							System.out.println("MONTH");
							np.setRange(1, 36);
							break;
					}
				}

			});

			final AlertDialog selectDurationAlertDialog = selectDurationDialogBuilder.create();
			// Set positive button
			selectDurationAlertDialog.setButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// Display CONFIRMATION_DIALOG
						//	tejashree
						
							com.ascentive.finallyfast.NumberPicker np = 
								(com.ascentive.finallyfast.NumberPicker)selectDurationAlertDialog.findViewById(R.id.numpick);
							// Set default value of the number picker widget
							getFinallyFastApplication().setTargetDateDuration(np.getCurrent());
							
							showDialog(CONFIRMATION_DIALOG);
							return;
						}
					});
			// Set negative button
			selectDurationAlertDialog.setButton2("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});
			return selectDurationAlertDialog;
			
		case CONFIRMATION_DIALOG:
			li = LayoutInflater.from(this);
			View confirmationDialogView = li.inflate(R.layout.deep_clean_confirmation_dialog, null);
			AlertDialog.Builder confirmationDialogBuilder = new AlertDialog.Builder(this);
			confirmationDialogBuilder.setView(confirmationDialogView);
			// confirmationDialogBuilder.setMessage(getAllSelectedCategories());
			
			TextView confirmheadingtv = (TextView)confirmationDialogView.findViewById(R.id.headingText);
			confirmheadingtv.setText(R.string.confirmation_dialog_heading);
			
			TextView messagetv = (TextView)confirmationDialogView.findViewById(R.id.messageText);
			messagetv.setText(getAllSelectedCategories());
			// messagetv.setText(getCleanUpStatusOfAllSelectedCategories());
			
			AlertDialog confirmationAlertDialog = confirmationDialogBuilder.create();
			
			confirmationAlertDialog.setButton("Yes",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// Display progress bar for argument specified (3) seconds
							drawProgressBar();
							return;
						}
					});
			confirmationAlertDialog.setButton2("No",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});

			return confirmationAlertDialog;
		case CLEAN_STATUS_DIALOG:
			
			LayoutInflater factory = LayoutInflater.from(this);
			final View statusView = factory.inflate(R.layout.deep_clean_status_dialog, null);
			
			AlertDialog.Builder statusDialogBuilder = new AlertDialog.Builder(this);
			statusDialogBuilder.setView(statusView);
			
			TextView statusheadingtv = (TextView)statusView.findViewById(R.id.headingText);
			statusheadingtv.setText("Status");
			
			TextView statusmessagetv = (TextView)statusView.findViewById(R.id.messageText);
			statusmessagetv.setText(getCleanUpStatusOfAllSelectedCategories());
			
			AlertDialog statusAlertDialog = statusDialogBuilder.create();

			statusAlertDialog.setButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});
			
			return statusAlertDialog;
			
		default:
			break;
		}
		return null;
	}
	
	public void drawProgressBar()
	{	
//		ImageView customTitleViewImage = new ImageView(this);
//		customTitleViewImage
//				.setImageResource(R.drawable.clearing_selected_files);

		cleanningProgDialog = new ProgressDialog(this);
		cleanningProgDialog.setIndeterminate(true);
		cleanningProgDialog.setMessage("Clearing Selected files");
		cleanningProgDialog.setCancelable(true);
		cleanningProgDialog.show();
		// cleanningProgDialog.setContentView(R.layout.progressbar_dialog);

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				closeProgressBar();
				showDialog(CLEAN_STATUS_DIALOG);
			}
		};
		Thread checkUpdate = new Thread() {
			public void run() {
				//
				// YOUR LONG CALCULATION (OR OTHER) GOES HERE
				//
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				onConfirmationDoClean();
				handler.sendEmptyMessage(0);
			}
		};
		checkUpdate.start();
        
	}
	public void closeProgressBar()
	{
	   cleanningProgDialog.dismiss();
	   cleanningProgDialog = null;
	}
	   
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		
		AlertDialog alertDialog = null;
		switch (id) {
		case SELECT_DURATION_DIALOG:

			alertDialog = (AlertDialog) dialog;
			
			// Set WEEK selected default value listview 
			// alertDialog.getListView().setItemChecked(WEEK, true);
			
			com.ascentive.finallyfast.NumberPicker np = 
				(com.ascentive.finallyfast.NumberPicker)alertDialog.findViewById(R.id.numpick);
			// Set default value of the number picker widget
			np.setCurrent(1);
			
			break;
			
		case CONFIRMATION_DIALOG:
			
			alertDialog = (AlertDialog) dialog;
			
			//TextView messagetv = (TextView)dialog.findViewById(R.id.messageText);
			//messagetv.setText(getAllSelectedCategories());
			//System.out.println(getAllSelectedCategories());
			
			break;
			
		default:
			break;
		}
	} 

	@Override
	public void onClearSelectedButtonPressed() {
		String s = getAllSelectedCategories();
		
		if(s == null || s.length() == 0 )
			Utility.DisplayToast(DeepCleanPage.this, "No Items are selected");
		else if(getClipboardDataSelected() == true)
		{
			Log.v(null, "only ClipboardData is selected - " + getClipboardDataSelected()); 
			showDialog(CONFIRMATION_DIALOG);
		}
		else
		{
			Log.v(null, "display select duration dialog" );
			showDialog(SELECT_DURATION_DIALOG);
		}
		return;
	}
	public void onConfirmationDoClean() {
		int i = 0;
		for (DeepCleanListItem item : mGroupNames) {
				if (item.isCheckBoxValue()) {
					Log.v(null, "Cleaning " + item.getItemName());
					item.doClean();
				}
				else
				{
				ArrayList<DeepCleanListItem> childArray = mChildrenNames.get(i);
				if (childArray != null) {
					for (DeepCleanListItem childItem : childArray) {
						if (childItem.isCheckBoxValue()) {
							Log.v(null, "Cleaning " + childItem.getItemName());
							childItem.doClean();
						}
					}
				}
				}
				i++;
		}		
		// mDeepCleanView.refreshMemoryStatus();
	}
	@Override
	public void onCheckBoxPressed(boolean isChecked) {
		processCheckAll(isChecked);
	}

	private void processCheckAll(boolean isChecked) {
		
		for (DeepCleanListItem item : mGroupNames) {
			item.setCheckBoxValue(isChecked);
			
			for(int i = 0; i < mGroupNames.size(); i++){
	    			ArrayList<DeepCleanListItem> list = mChildrenNames.get(i);
	    			if(list == null)
	    				continue;
	    			for(DeepCleanListItem child: list){
	    				child.setCheckBoxValue(isChecked);
	    			}
	    		}
		}
		// mDeepCleanListAdapter.notifyDataSetChanged();
		expListAdapter.notifyDataSetChanged();
	}
	public void notifyAdapterChanged() 
	{
		expListAdapter.notifyDataSetChanged();
	}

	// @Override
	public void onItemChecked(DeepCleanListItem item) {
		if (item.isCheckBoxValue() == false)
			mDeepCleanView.uncheckCommonChkBox();
	}
	// @Override
	public void onItemChecked(ArrayList<DeepCleanListItem> itemList, boolean isChecked) {
		for (DeepCleanListItem item: itemList)
		{
		if (item.isCheckBoxValue() == false)
			mDeepCleanView.uncheckCommonChkBox();
		}
	}
	
	public String getAllSelectedCategories()
	{
		String returnString = new String();
		int i = 0;
		for (DeepCleanListItem item : mGroupNames) {
				
				if (item.isCheckBoxValue()) {
					
					returnString += "\n";
					Log.v(null, "Ask for " + item.getItemName());
					returnString += item.getItemName();
				}
				
				ArrayList<DeepCleanListItem> childArray = mChildrenNames.get(i);
				if (childArray != null) {
					for (DeepCleanListItem childItem : childArray) {
						if (childItem.isCheckBoxValue()) {
	
							returnString += "\n";
							Log.v(null, "Ask for " + childItem.getItemName());
							returnString += childItem.getItemName();
						}
					}
				}
				i++;
		}		
		return returnString;
	}
	public boolean getClipboardDataSelected()
	{
		boolean isOnlyClipBoardSelected = false;
		int i = 0;
		for (DeepCleanListItem item : mGroupNames) {
				
			if (item.isCheckBoxValue()) {

				if (item.getItemName().equals(this.getResources().getString(R.string.clipboard_data))
						|| item.getItemName().equals(this.getResources().getString(R.string.android_market_serach_history))
						|| item.getItemName().equals(this.getResources().getString(R.string.gmail_search_history))
						|| item.getItemName().equals(this.getResources().getString(R.string.google_maps_search_history))
						|| item.getItemName().equals(this.getResources().getString(R.string.android_market_serach_history)) ) {
					Log.v(null, "Ask for " + item.getItemName() + " "
							+ item.isCheckBoxValue());
					isOnlyClipBoardSelected = true;
				} else {
					Log.v(null, "Ask for " + item.getItemName() + " "
							+ item.isCheckBoxValue());
					isOnlyClipBoardSelected = false;
					return isOnlyClipBoardSelected;
				}
			}
				
				ArrayList<DeepCleanListItem> childArray = mChildrenNames.get(i);
				if (childArray != null) {
					for (DeepCleanListItem childItem : childArray) {
						if (childItem.isCheckBoxValue()) {
	
							Log.v(null, "Ask for " + childItem.getItemName() + " " + childItem.isCheckBoxValue() );
							isOnlyClipBoardSelected = false;
							return isOnlyClipBoardSelected;
						}
					}
				}
				i++;
		}
		
		return isOnlyClipBoardSelected;
	}
	
	public String getCleanUpStatusOfAllSelectedCategories()
	{
		String returnString = new String();
		
		int i = 0;
		for (DeepCleanListItem item : mGroupNames) {
				
				if (item.isCheckBoxValue()) {
					
					returnString += "\n";
					Log.v(null, "Ask for " + item.getItemName());
					returnString += item.getItemName();
					returnString += "  :  ";
					if( item.numberOfFileCleaned() == -1) returnString += "All";
					else returnString += item.numberOfFileCleaned();
				}
				
				ArrayList<DeepCleanListItem> childArray = mChildrenNames.get(i);
				if (childArray != null) {
					for (DeepCleanListItem childItem : childArray) {
						if (childItem.isCheckBoxValue()) {
	
							returnString += "\n";
							Log.v(null, "Ask for " + childItem.getItemName());
							returnString += childItem.getItemName();
							returnString += "  :  ";
							if(childItem.numberOfFileCleaned() == -1) returnString += "All";
							else returnString += childItem.numberOfFileCleaned();
						}
					}
				}
				i++;
		}		
		
		return returnString;
	}
	
}
